# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""FasterRCNN"""
from mindspore.train.serialization import load_checkpoint, load_param_into_net

from models.meta_arch.two_stage_detector import TwoStageDetector
from utils.class_factory import ClassFactory, ModuleType
from utils.logger import get_root_logger


@ClassFactory.register(ModuleType.DETECTOR)
class FasterRCNN(TwoStageDetector):
    """
    FasterRCNN detection module
    """
    def init_weights(self, config):
        logger = get_root_logger()
        ckpt_path = config.pretrained_checkpoint
        if ckpt_path and ckpt_path != "":
            param_dict = load_checkpoint(ckpt_path)
            logger.info("param dict:\n {}".format(param_dict))
            load_param_into_net(self, param_dict)


class FasterRCNNInfer(TwoStageDetector):
    """FasterRCNN Infer"""
    def __init__(self, config, backbone, neck, rpn_head, roi_head, train_cfg, test_cfg):
        super().__init__(config, backbone, neck, rpn_head, roi_head, train_cfg, test_cfg)
        self.set_train(False)

    def construct(self, img_data, img_metas):
        output = self(img_data, img_metas, None, None, None)
        return output
